package com.hxut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxut.entity.SysMenu;
import com.hxut.entity.SysRole;
import com.hxut.entity.SysUser;
import com.hxut.mapper.SysMenuMapper;
import com.hxut.mapper.SysUserMapper;
import com.hxut.service.SysMenuService;
import com.hxut.service.SysRoleService;
import com.hxut.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxut.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MR.S
 * @since 2022-06-21
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    @Override
    public String getAuthorityInfo(Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        ////ROLE_admin,ROLE_normal,sys:user:list..
        String authoritys = "";

        if (redisUtils.hasKey("GrantedAuthority:" + sysUser.getUsername())) {
             authoritys=(String) redisUtils.get("GrantedAuthority:" + sysUser.getUsername());
             // System.out.println(authoritys);
             return authoritys;
        }
        //查询角色
        List<SysRole> sysRoles = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id  from sys_user_role where user_id=" + userId));
        if(sysRoles.size()>0){
            String rolesCode=sysRoles.stream().map(item->
                    "ROLE_"+item.getCode()).collect(Collectors.joining(","));
            authoritys=rolesCode.concat(",");

        }

        //查询操作菜单权限
        List<Long> menuIds=sysMenuMapper.getMenuIds(userId);
        if(menuIds.size()>0){
            List<SysMenu> sysMenus = sysMenuService.listByIds(menuIds);
            String menuPerms=sysMenus.stream().map(item->item.getPerms()).collect(Collectors.joining(","));
            authoritys=authoritys.concat(menuPerms);
        }

        //缓存权限信息
        redisUtils.set("GrantedAuthority:" + sysUser.getUsername(), authoritys, 60 * 60);


        return authoritys;

    }


    //当用户权限被更改时清除缓存
    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtils.del("GrantedAuthority:" + username);
    }

    //当角色权限被改变时清除缓存
    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        //角色权限被修改时，用户也要进行删除
        //只要和角色关联的userid的缓存都要清除
        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>()
                .inSql("id", "select user_id from sys_user_role where role_id=" + roleId));
        sysUsers.forEach(user->{
            this.clearUserAuthorityInfo(user.getUsername());
        });

    }

    //当菜单管理权限发送改变时，清除缓存
    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        //菜单管理权限发送改变时，用户和角色也会改变
        List<SysUser> sysUsers=sysMenuMapper.listByMenuId(menuId);
        sysUsers.forEach(user->{
            this.clearUserAuthorityInfo(user.getUsername());
        });
    }
}
